package cn.com.nes.site.config;

import cn.com.nes.site.handle.convert.EnumConvertFactory;
import cn.com.nes.site.interceptor.AuthInterceptor;
import cn.com.nes.site.interceptor.GlobalApiLogInterceptor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;


@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Resource
    private GlobalApiLogInterceptor globalApiLogInterceptor;

    @Resource
    private AuthInterceptor authInterceptor;

    @Resource
    private EnumConvertFactory convertFactory;

    @Override
    public void addFormatters(FormatterRegistry formatterRegistry) {
        formatterRegistry.addConverterFactory(convertFactory);
    }

    /**
     * 方式二：配置MessageConverter
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //Jackson的全局序列化方式
        configureJacksonHttpMessageConverter(converters);
    }

    /**
     * Jackson的全局序列化方式
     * @param converters
     */
    private void configureJacksonHttpMessageConverter(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //反序列化的时候如果多了其他属性,不抛出异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //日期格式处理
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }


    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {

    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {

    }

    @Override
    public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {

    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {

    }

    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {

    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {

    }

    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        // 注册日志记录拦截器
        interceptorRegistry.addInterceptor(globalApiLogInterceptor)
                .addPathPatterns("/**")
                // 登录放行
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/v2/app/userReg", "/v2/app/sendValidCode", "/v2/app/login")
                // swagger 放行
                .excludePathPatterns("/swagger*/**", "/v2/api-docs", "/webjars/**");


        // 注册权限验证拦截器
        interceptorRegistry.addInterceptor(authInterceptor)
                .addPathPatterns("/v2/**")
                .excludePathPatterns("/v2/app/userReg", "/v2/app/sendValidCode", "/v2/app/login")
                // 项目 放行
                .excludePathPatterns("/v2/project/service/user/getMyTeamInfoList", "/v2/system/user/checkIsForeman", "/v2/project/service/user/validHeadServiceUser", "/v2/project/service/user/getMyTeamProjectList", "/v2/project/service/user/getMyTeamMemberList", "/v2/project/service/user/getMyTeamWorkArea")
                // 工单 放行
                .excludePathPatterns("/v2/order/work/getAllWorkOrderPage", "/v2/order/work/getMyTeamWorkOrderInstallPage", "/v2/order/work/distributeWorkOrder", "/v2/order/work/distributeWorkOrderByAreaCode", "/v2/order/work/captainCancelWorkOrders")
                // 用户权限 放行
                .excludePathPatterns("/v2/system/user/getAuthToken", "/v2/system/user/getAuthTokenByErUserId", "/v2/system/user/updateUserInfoFromEasyRepair")
                // 动态页面详情 放行
                .excludePathPatterns("/v2/h5/getDynamicPosterDetail", "/v2/h5/getActiveDetail")
                // swagger 放行
                .excludePathPatterns("/swagger*/**", "/v2/api-docs", "/webjars/**")
                // 公司 放行
                .excludePathPatterns("/v2/system/company/queryAgentCompany", "/v2/agent/grant/queryAgentSupplierIds");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry viewControllerRegistry) {

    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {

    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {

    }

    @Override
    public Validator getValidator() {
        return null;
    }

    @Override
    public MessageCodesResolver getMessageCodesResolver() {
        return null;
    }

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("UTF-8");
        multipartResolver.setMaxUploadSize(1024 * 1024 * 5);//设置上传文件大小为30M
        // multipartResolver.setMaxUploadSizePerFile(1024 * 1024 * 10);//设置单个上传文件大小为10M
        return multipartResolver;
    }

}
